package com.heima.media.task;

import com.heima.media.entity.WmNews;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author: itheima
 * @create: 2022-07-04 15:39
 */
@Slf4j
@Component
public class MediaTask {

    @Autowired
    private RedissonClient redissonClient;


    @Autowired
    private IAuditService auditService;

    @Autowired
    private IWmNewsService wmNewsService;

    /**
     * 轮询监听延迟任务消息
     */
    @Async("leadnewsExecutor")
    public void handleMsg() {
        try {
            RBlockingDeque<String> blockingDeque = redissonClient.getBlockingDeque("test-dqueue");
            //从阻塞队列取出队首的元素，如果在指定时间内，队列一旦有数据立即返回队列中数据。否则直到时间超时还没有数据可取，返回null
            while (true) {
                String wmNewId = blockingDeque.poll(30, TimeUnit.SECONDS);
                if (StringUtils.isNotBlank(wmNewId)) {
                    log.info("监听到延迟消息：{}", wmNewId);
                    WmNews wmNews = wmNewsService.getById(wmNewId);
                    auditService.audit(wmNews);
                }
            }
        } catch (InterruptedException e) {
            log.error("监听延迟发布消息失败：{}", e);
        }
    }

}
